const { PickDao } = require('../dao/pick');
/* ======== Action Logic ============ */
const PickAction = {

    async addOne({ name, phone, department, ip }) {
        console.log('From PickAction.addOne');
        return new Promise((reslove, reject) => {
            PickDao.searchOne({ name, phone }, rtn => {
                if (rtn.err) return reject({ err: rtn.err });
                if (rtn.row) {
                    console.log('rtn in PickAction.addOne',rtn);
                    return reject({ found: rtn.row });
                } else {
                    PickDao.addOne({ name, phone, department, ip }, rtn2 => {
                        if (rtn2.err) return reject({ err: rtn2.err });
                        console.log('rtn2 in PickAction.addOne',rtn2);
                        reslove({ ok: true })
                    });
                }
            });
        });
    },

    async searchOne({ name, phone }) {
        console.log('From PickAction.searchOne', { name, phone });
        return new Promise((reslove, reject) => {
            PickDao.searchOne({ name, phone }, rtn => {
                console.log('rtn in PickAction.searchOne', rtn)
                if (rtn.err) return reject({ err: rtn.err });
                if (rtn.row) return reslove({ row: rtn.row });
                // found Nothing.
                return reslove({ row: null });
            });
        });
    },

    async getList() {
        console.log('From PickAction.getList');
        return new Promise((reslove, reject) => {
            PickDao.getList((rows, err) => {
                if (err) return reject(err);
                if (rows) return reslove(rows);
            });
        });
    },

    async delOne(id) {
        console.log('From PickAction.delOne');
        return new Promise((reslove, reject) => {
            PickDao.delOne(id, (err, rows) => {
                if (err) return reject({ err });
                if (rows) return reslove({ rows });
            });
        });
    }
}

/* ==== Router Regist  ============ */

const getUserIp = req => {
    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
};

const PickRouter = router => {

    router.put('/action/pick', async (ctx, next) => {
        console.log('PUT pick');
        let { name, phone, department } = ctx.request.body;
        ctx.set('Content-Type', 'application/json');
        if (!name || !phone || !department) {
            ctx.status = 403;
            ctx.body = { error: '参数错误' };
            return next();
        }
        let ip = getUserIp(ctx.req);
        try {
            let rtn = await PickAction.addOne({ name, phone, department, ip });
            if (rtn.err) {
                ctx.status = 500;
                ctx.body = { error: '提交失败' };
                return next();
            }
            ctx.body = { ok: true };
        } catch (error) {
            ctx.body = { error };
            ctx.status = 504;
        }

        next();
    });

    router.post('/action/pick', async (ctx, next) => {
        let { name, phone } = ctx.request.body;
        ctx.set('Content-Type', 'application/json');
        if (!name && !phone) {
            ctx.status = 403;
            ctx.body = { error: '参数错误' };
            return next();
        }
        try {
            let rtn = await PickAction.searchOne({ name, phone });
            if (rtn.err) {
                ctx.status = 500;
                ctx.body = { error: '查询失败' };
            }

            if (rtn.row) {
                ctx.body = { row: rtn.row };
            }
        } catch (error) {
            ctx.body = { error };
            ctx.status = 504;
        }
        next();
    });

    router.get('/action/pick', async (ctx, next) => {
        console.log('GET picks ');
        ctx.set('Content-Type', 'application/json');
        try {
            let rows = await PickAction.getList();
            // console.log('Found Rows',rows);
            ctx.body = rows;
        } catch (error) {
            ctx.body = { error };
            ctx.status = 504;
        }
        next();
    });

    router.delete('/action/pick/:id', async (ctx, next) => {
        console.log('DELETE pick :# ', ctx.params.id);
        ctx.set('Content-Type', 'application/json');
        try {
            await PickAction.delOne(ctx.params.id);
            ctx.status = 204;
            ctx.body = { msg: 'OK' };
        } catch (error) {
            ctx.status = 504;
            ctx.body = { error };
        }
        next();
    });


}

module.exports.PickRouter = PickRouter;